import math
import os
from pymt import *
from OpenGL.GL import GL_LINE_STRIP, glColor4f, glVertex2f, GL_LINE_BIT, glLineWidth
from OpenGL.GL import glTranslatef
import Gwen.MTPagesViewer as MTPagesViewer
import Gwen.MTPicture as MTPicture
import Gwen.MTText as MTText
import Gwen.TransformToXML as TransformToXML
current_dir = os.path.dirname(__file__)

def gesture_add_default(gdb):
    # Circle
    g = gdb.str_to_gesture('eNqdWk2PHDcOvfcf8VwyEL8k8h5ksbcF/AMWjjPwBpt4GtNjIPn3q5LYVaxYqupsH9oYztMr1SNFvqrx06/XP39/f/7ycnv/9vZy+Yf/e02Xp1+ucPn44fb+9vrfl9uHyxUvT79d6fI0XPGxwS5XXtZJXXd9/fXr+7IsL8vKZNm/FtTlqssqq6v+rAsgXX5Kz6iskIoZgRUsmi+3jx/+WH4Ny69B2VitmBgoFYLL7edPh9cAbLdEly/9AgTCSIkZoWQtSS+3L507ZZRzunanICsdiRJgKqxYN13udD9UPjAgzEIpAyKLnpPnRl5WcpSMBVBUEnGispEDgyjkO396QIimNthKngRBLTu75I0cibjKmwtxNtJzbmx1g3DnHmTxzl31TwIJE6e6f8x2Tt4yiGsGEYgUsdIagJSEgVwze20smy/n+cSWT1zzCVjrQ9g3bhwkZymWVs3F8Jy85RPXfCYyg6pNAspJmCWQq4prsvA/UInY8omez6XeBAxJjUWK1hI32OglqaFKAW7ftcTO6KmllGClByGr6kJSZZKaxrB504J8P5elPMDeckq0si/nIwHf976UxcqeFZYD5Px10Sl7SyrJyk5QKmmCklLWhBxKhmtESxGvyfzA3ltWqWzsWVESozT+EtNaG422M9Sv8IjuLa20pZWTpZyLk5vFc4qEntHlW87PEresMjzCXo8CeAdYdp/O+xe3rPKWVa4VWVss3T+wNdsEuIpeTzM9Qt/SyvIIfT3AsWbwAWlaWjmk1VRrg/KayXljBxO4t/V6BT2vSG5Z5S2rdVLUNiONumCYQlhy2Q6qnFNLS6lsKSUsXKeFaabWC8rKXQs1b6KAnDd2aRmV83Nak8HpbzZ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8GozL7e7ybQ5xm69wAOkKKs2PoRt95QNIV1AlnnC3+lp2wa6S6i7YdVHbBbsudtBY3OAbzNuTO3zDOcQtvlFsju7qjXfBrkQzvJNm7E7eSmzi3cpruk+E0TrpEJjPo27tNdF8/nVvr+lginZzr0nmA7q7e015Ouaxe/07ZOQgsHv9DTJiwQ5pYkk3s9jd/T2IQ2qOEPZ1rqBOXRemHCE6pC4BkpNTawzCkNoiZDSEEVKElCEEIqRbDgQMwZKG6yhC0NdxDNJwnQQhh+4eIYc0FnHqEoqoDCsEYp35AweCxeCwbDAFiD/gIEKo6+GDESKG06FeE+i64PSZC5HDwRs+uaH7ebPp8x+6nzedPkWiu/veGfzpE93PexCG1Baajg2Lz/28yQEk9jN/Zkb3873zDZ+10f38ChlRc2ix/jIA3c/b/B0Uup+3+csMpDgDJhANs8Nfk6C7+z5l7kH38zp/HYTu7lUOIHEaTiAUZuoC2W+7QXw24gFEwvCeQHxupg7xc+9mv5R91B0F76NuIvYM7umzM9DgHt3TZzmAuPOiAwgFoziB8O5F4BAif4F8r5Q7/PvLwiGk7N4WDiH+QjEfQGz3vnAEcfcvdADxd4p4AMHda8chpKsrB+r6UwPrAcTfOe7LyR8U/hqtGvY34u+v3z7/558/Lv/xpT4NfPzw++u32wu3H+3Sfv/by9unr59fllDpf59J+w8sOH9l/+/r2+sv3z6/NzTU2fjMUBuIScLlr+hL7Pbz8/8A9Aw2sQ==')
    g.label = 'Circle'
    g.id = 'circle'
    gdb.add_gesture(g)
    
    # NUI-wave
    g = gdb.str_to_gesture('eNq1lttqHEcURd/7R6SXiHO//IDzGtAHBMcehIljDZoxxH+f3eXRdCskKSVBQiDBTK2urnVqn3P76fjtt/Pdw+F0/vp0WH68/D3ScvvxyMv9zen89Pjr4XSzHGW5/XzU5fYvV9yPry1HW9c51h0fP305r8tiXZZ/s+yn9VvLsdZVjVXfsIBpefcD3UmIsXqGRlJY53K6v/l9/ZzH566cxmSqUe0kupx+ef+PT2EZL6XLw+URXKwq1i7lXVpAPPx3+nh19o0u5MJRZumcSv2/6DHoeaUTNyepKouWcOaOziWSLl3uphGvoA8B3N/pgFtpp6iZaZp3x0a3xosRNl1SRh0xpcsoJuFnOmN3wu6VUZQELRvccS6R3GQW4tVz+JAq+jbw4VT8Cs/I9GC8u7CY1A4O0xmc5WRUrjKHD6WSz3ARo5RmYm5D4fgGR2lSi7alkBK7zeHDqFyNimNnEa1Nirq0XakrXc5K2ztzvnEdPpVfwRbL9hRvL+eIVxS6Dp969SlM7kBHkDcV7SqRn5+I68TwPvepw6duPtk7rEhw5oqwsR1cu1DqzpZJXjo/ch0+Nd8GPnzqdkPd2bWf76Lnrs6pG06DqTWQPO5Tug2jxrt0+VP48g4f7mIlyS6pmllz/pBqW/Jie6nZRNGs1cq7w6GX4Ug0TxgbXm2XvZHF1YVcRAmOgB140OHDJI2MEXKa4a/Y/jBr+Vb44db6ihepkM5GRqnUNcLWo/GSwOlzw2+6zuE+1PqmFp2hJQm7L8LFtdjogT6oKCwRD0O6zS+UD7G+iUVOJSNQ0HbQemR3Moxgcyorx01FWs6t+vdhYrMqHdxAX0BpGzwzuUClxnXoeYb5UOqbUvQM5hDUZDRSfjsV8ZdGc84ePn3zyQj25nZDL0VHlR0cV9WIQGVBSPA8CGL4DH4b+NAZu3uajSpnU5BCBZlzpasrGhJhColgdL15KcbwGZtP5Na+FNVyo1fCaSG8DNNH1TzDYhiNa/ySWpWiYSIMRdE86wqHzn9XLTGMxpa+mLgK9XyZs1AvGxsdryoKyUmJf+fwHEZzOh6BHSh8YShJk5ael2IOoblNR425DU0jVD00a3cmUetIhD6uyN7ucffX3/ub8+Pnw9P7Lx8OGL5x51YMvfzhdTa/7ODn49Pjx68fzuuXfXlnd4FpBhdK1kMThD7Ad38A6q5S7Q==')
    g.label = 'NUI-wave'
    g.id = 'NUI-wave'
    gdb.add_gesture(g)

def action_close_menu(menu, w, args, *largs):
    menu.parent.remove_widget(menu)
    del menu

def action_close_all(menu, w, args):
    sys.exit()

def action_launch_plugin(menu, w, plugin, *largs):
    pos = w.parent.to_parent(*w.pos)
    win = MTInnerWindow(size=(320,280), pos=pos)
    plugins.activate(plugin, win)
    menu.parent.add_widget(win)

    action_close_menu(menu, w, None)

def addExternalContent():
    # add pictures    	
	picture1 = MTPicture.MTPicture(filename='./Gwen/content/pic1.jpg', pos=(280,120), listPages=listPages, kinetics=kinetics)
	kinetics.add_widget(picture1)
	picture2 = MTPicture.MTPicture(filename='./Gwen/content/pic2.jpg', pos=(10,10), listPages=listPages, kinetics=kinetics)
	kinetics.add_widget(picture2)
	picture3 = MTPicture.MTPicture(filename='./Gwen/content/pic3.jpg', pos=(170,10), listPages=listPages, kinetics=kinetics)
	kinetics.add_widget(picture3)
	picture4 = MTPicture.MTPicture(filename='./Gwen/content/pic4.jpg', pos=(260,10), listPages=listPages, kinetics=kinetics)
	kinetics.add_widget(picture4)
	picture5 = MTPicture.MTPicture(filename='./Gwen/content/pic5.jpg', pos=(150,130), listPages=listPages, kinetics=kinetics)
	kinetics.add_widget(picture5)
	picture6 = MTPicture.MTPicture(filename='./Gwen/content/pic6.jpg', pos=(10,130), listPages=listPages, kinetics=kinetics)
	kinetics.add_widget(picture6)	
    # add texts
	text1=MTText.MTText(filename='/content/text1.txt',pos=(10,280), size=(200,300),listPages=listPages,kinetics=kinetics)
	kinetics.add_widget(text1)
	text2=MTText.MTText(filename='/content/text2.txt',pos=(10,440), size=(200,300),listPages=listPages,kinetics=kinetics)
	kinetics.add_widget(text2)
	text3=MTText.MTText(filename='/content/text3.txt',pos=(90,250), size=(200,300),listPages=listPages,kinetics=kinetics)
	kinetics.add_widget(text3)
	text4=MTText.MTText(filename='/content/text4.txt',pos=(250,270), size=(200,300),listPages=listPages,kinetics=kinetics)
	kinetics.add_widget(text4)
	text5=MTText.MTText(filename='/content/text5.txt',pos=(10,500), size=(200,300),listPages=listPages,kinetics=kinetics)
	kinetics.add_widget(text5)
	text6=MTText.MTText(filename='/content/text6.txt',pos=(310,230), size=(200,300),listPages=listPages,kinetics=kinetics)
	kinetics.add_widget(text6)			
	
def removeExternalContent(content):
    kinetics.remove_widget(content)

class MTGestureDetector(MTGestureWidget):
    def __init__(self, gdb, **kwargs):
        super(MTGestureDetector, self).__init__(**kwargs)
        self.gdb = gdb
        self.dt = 0
        self.inactivity = 0
        self.inactivity_timeout = 5

    def on_touch_down(self, touch):
        touch.userdata['desktop.gesture'] = list(touch.pos)
        return super(MTGestureDetector, self).on_touch_down(touch)

    def on_touch_move(self, touch):
        if 'desktop.gesture' in touch.userdata:
            touch.userdata['desktop.gesture'] += list(touch.pos)
        return super(MTGestureDetector, self).on_touch_move(touch)

    def draw(self):
        # draw gestures
        set_color(1, 1, 1, .6)
        for touch in getCurrentTouches():
            if not 'desktop.gesture' in touch.userdata:
                continue
            drawLine(touch.userdata['desktop.gesture'], width=5.)

        if len(getCurrentTouches()):
            self.inactivity = 0
            return
        self.inactivity += getFrameDt()
        if (self.inactivity < self.inactivity_timeout) or (len(self.parent.children) > 1):
            return # do not draw the prompting circle
            
        alpha = (self.inactivity - self.inactivity_timeout) / 3.
        alpha = boundary(alpha, 0, 1.)

        w = self.get_parent_window()
        s2 = Vector(w.size) / 2.
        self.dt += getFrameDt() * 2

        step = math.pi / 20.
        radius = 50
        i = 0
        with DO(gx_attrib(GL_LINE_BIT), gx_blending):
            glLineWidth(3)
            with gx_begin(GL_LINE_STRIP):
                while i < math.pi * 2:
                    x, y = math.cos(self.dt - i) * radius, math.sin(self.dt - i) * radius
                    glColor4f(1, 1, 1, min(alpha, i / math.pi))
                    glVertex2f(x + s2.x, y + s2.y - 70)
                    i += step

            set_color(1, 1, 1, alpha)
            drawCircle(pos=(x + s2.x, y + s2.y - 70), radius=4)
            drawCircle(pos=(x + s2.x, y + s2.y - 70), radius=20, linewidth=2)

        label='Draw a circle to make the menu appear'
        k = {'font_size': 24, 'bold': True}
        pos = Vector(w.size) / 2. + Vector(0, 10)
        drawLabel(label=label, pos=pos, color=(.5, .5, .5, min(alpha, .5)), **k)
        pos += Vector(1, -1)
        drawLabel(label=label, pos=pos, color=(1, 1, 2, alpha), **k)

    def on_gesture(self, gesture, touch):
        #print self.gdb.gesture_to_str(gesture)
        try:
            #score, best = self.gdb.find(gesture, minscore=.7)
            score, best = self.gdb.find(gesture, minscore=.8)
        except Exception, e:
            return
      


if __name__ == '__main__':

    # load css for ICE table
    css_file = open("ICETable.css", "r")
    css = css_file.read()
    css_add_sheet(css)
    
    # Create and fill gesture database
    gdb = GestureDatabase()
    gesture_add_default(gdb)

    # Create background window
    w = getWindow()
    w.wallpaper = 'resources/black.jpg'
    w.wallpaper_position = 'scale'

    # add gesturing
    gesturing = MTGestureDetector(gdb)
    w.add_widget(gesturing)
  
    # add kinetics to everything
    kinetics = MTKinetic()
    w.add_widget(kinetics)
	
	#Create a pageviewer
    size = w.size
    page_viewer = MTPagesViewer.MTPagesViewer(size = (720, 100), pos=((size[0]/2)-360, (size[1]-140)), rotation=0, kinetics=kinetics, parent_size=w.size)
    kinetics.add_widget(page_viewer)
    listPages=page_viewer._get_listPages()
    listMiniatures=page_viewer._get_listMiniatures()
	
	#Add pictures and texts
    addExternalContent()
	
	#Add publish button
    publish_button=MTButton(label="Publish", pos=(10, (size[1]-60) ), size=(100,50), cls="miniature")
    kinetics.add_widget(publish_button)	
    @publish_button.event
    def on_release (touch):
		xml=TransformToXML.TransformToXML(listPages,listMiniatures)

    runTouchApp()
